package com.lds.erp.product;

import java.util.List;

import com.dph.common.utils.base.Money;
import com.dph.common.utils.core.exception.BizError;
import com.lds.erp.base.baseset.SalesSetFacade;
import com.lds.erp.base.baseset.order.SalesSetQueryOrder;
import com.lds.erp.base.baseset.result.SalesSetQueryResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dph.common.utils.base.PageEntity;
import com.dph.common.utils.utils.AppUtils;
import com.lds.erp.base.JsonResult;
import com.lds.erp.common.YNEnum;
import com.lds.erp.common.util.AccountCache;
import com.lds.erp.common.util.AccountUtils;
import com.lds.erp.order.OrderCartClient;
import com.lds.erp.order.cart.order.OrderCartDetailOrder;
import com.lds.erp.order.cart.result.OrderCartDetailResult;
import com.lds.erp.order.cart.vo.AppSsuListVO;
import com.lds.erp.product.ao.PtSsuBuyedPageAO;
import com.lds.erp.product.ao.PtSsuDetailAO;
import com.lds.erp.product.ao.PtSsuSearchPageAO;
import com.lds.erp.product.ssu.PtSsuFacade;
import com.lds.erp.product.ssu.info.PtSsuVo;
import com.lds.erp.product.ssu.order.PtSsuDetailOrder;
import com.lds.erp.product.ssu.order.PtSsuPurchasePageOrder;
import com.lds.erp.product.ssu.order.PtSsuSearchPageOrder;
import com.lds.erp.product.ssu.result.PtSsuDetailResult;
import com.lds.erp.product.ssu.result.PtSsuSearchPageResult;
import com.lds.erp.product.ssu.info.PtSsuDetailVo;
import com.lds.erp.product.vo.PtSsuQueryVo;
import com.lds.erp.util.JsonUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;

import static com.lds.erp.gateway.interceptor.SignValidInterceptor.TOKEN_PARAM_KEY;

/**
 * @author yyc
 */
@RestController
@RequestMapping(value = "/api/product/")
@Api(value = "商品信息", description = "商品信息", tags = {"小程序商品相关接口"})
public class ProductController {
    private static final Logger logger = LoggerFactory.getLogger(ProductController.class);

    @Reference(version = "1.0")
    private PtSsuFacade ptSsuFacade;

    @Autowired
    private OrderCartClient orderCartClient;

    @Reference(version = "1.0")
    private SalesSetFacade salesSetFacade;


    @ApiOperation(value = "小程序商品查询列表(senilon)", notes = "小程序首页商品查询列表,根据推荐/畅销/新品/分类id等方式查商品")
    @GetMapping("product_search_list")
    public JsonResult<PtSsuSearchPageResult> productSearchList(HttpServletRequest request, PtSsuSearchPageAO ao) {
        String serialNo = AppUtils.newNo();
        PtSsuSearchPageOrder ssuSearchOrder = new PtSsuSearchPageOrder();
        ssuSearchOrder.setSerialNo(serialNo);
        BeanUtils.copyProperties(ao, ssuSearchOrder);
        if (null == ssuSearchOrder.getSkuStatus()) {
            ssuSearchOrder.setSkuStatus(YNEnum.Y);
        }
        // 获取登录的移动端
        if (null == ao.getPageNum()) {
            ao.setPageNum(1);
        }
        if (null == ao.getPageSize()) {
            ao.setPageSize(10);
        }
        AccountCache accountCache = null;
        String token = request.getHeader(TOKEN_PARAM_KEY);

        if (token != null)
        {
            accountCache = AccountUtils.getAccount(token);
        }

        if (accountCache == null)
        {
            accountCache = AccountUtils.getAccount();
        }

        ssuSearchOrder.setPage(new PageEntity<>(ao.getPageNum(), ao.getPageSize()));
        ssuSearchOrder.setMchId(accountCache.getMchId());
        PtSsuSearchPageResult result = ptSsuFacade.ssuSearchByPage(ssuSearchOrder);
        // 设置列表中购物车商品数量
        setCartProductNum(serialNo, result, token);
        return result.isSuccess() ? JsonUtils.success(result) : JsonUtils.fail(result.getMessage());
    }


    @ApiOperation(value = "活动板块商品", notes = "活动板块商品")
    @GetMapping("product_activity_search_list")
    public JsonResult<PtSsuQueryVo> productActivitySearchList(HttpServletRequest request, PtSsuSearchPageAO ao) {
        String serialNo = AppUtils.newNo();
        PtSsuSearchPageOrder ssuSearchOrder = new PtSsuSearchPageOrder();
        ssuSearchOrder.setSerialNo(serialNo);
        BeanUtils.copyProperties(ao, ssuSearchOrder);
        if (null == ssuSearchOrder.getSkuStatus()) {
            ssuSearchOrder.setSkuStatus(YNEnum.Y);
        }
        // 获取登录的移动端
        if (null == ao.getPageNum()) {
            ao.setPageNum(1);
        }

        ao.setPageSize(100);

        ssuSearchOrder.setPage(new PageEntity<>(ao.getPageNum(), ao.getPageSize()));
        PtSsuSearchPageResult result = ptSsuFacade.ssuSearchactivityByPage(ssuSearchOrder);
        String token = request.getHeader(TOKEN_PARAM_KEY);
        // 设置列表中购物车商品数量
        setCartProductNum(serialNo, result, token);
        return result.isSuccess() ? JsonUtils.success(result, PtSsuQueryVo.class) : JsonUtils.fail(result.getMessage());
    }


    @ApiOperation(value = "活动板块", notes = "活动板块")
    @GetMapping("product_activity_part_list")
    public JsonResult<PtSsuQueryVo> productActivityPartSearchList(HttpServletRequest request, PtSsuSearchPageAO ao) {
        String serialNo = AppUtils.newNo();
        PtSsuSearchPageOrder ssuSearchOrder = new PtSsuSearchPageOrder();
        ssuSearchOrder.setSerialNo(serialNo);
        BeanUtils.copyProperties(ao, ssuSearchOrder);
        if (null == ssuSearchOrder.getSkuStatus()) {
            ssuSearchOrder.setSkuStatus(YNEnum.Y);
        }
        // 获取登录的移动端
        if (null == ao.getPageNum()) {
            ao.setPageNum(1);
        }

        ao.setPageSize(100);


        PtSsuSearchPageResult result = ptSsuFacade.ssuSearchactivityByPage(ssuSearchOrder);

        return result.isSuccess() ? JsonUtils.success(result, PtSsuQueryVo.class) : JsonUtils.fail(result.getMessage());
    }


    /**
     * 设置列表中购物车商品数量
     *
     * @param result
     */
    private void setCartProductNum(String serialNo, PtSsuSearchPageResult result, String token) {
        OrderCartDetailOrder order = new OrderCartDetailOrder();
        AccountCache accountCache = AccountUtils.getAccount(token);
        // 允许用户先浏览
        if (null == accountCache) {
            return;
        }
        order.setSerialNo(serialNo);
        order.setCartMchId(accountCache.getMchId());
        order.setDistrictId(result.getDistrictId());
        OrderCartDetailResult cartDetail = orderCartClient.orderCartDetail(order);
        List<AppSsuListVO> ssuVOList = cartDetail.getSsuVOList();
        for (AppSsuListVO appSsuListVO : ssuVOList) {
            result.setTotalProductNum(result.getTotalProductNum().add(appSsuListVO.getOrdProductNum()));
        }

        if (null != result.getSsuVOList() && null != result.getSsuVOList().getList()
                && result.getSsuVOList().getList().size() > 0) {
            if (cartDetail.isFail()) {
                logger.error("获取购物车中商品数据错误{}", cartDetail.getMessage());
            } else {
                List<PtSsuVo> pageList = result.getSsuVOList().getList();
                if (null != ssuVOList && ssuVOList.size() > 0) {
                    for (AppSsuListVO appSsuListVO : ssuVOList) {
                        for (PtSsuVo item : pageList) {
                            if (appSsuListVO.getSsuCode().equals(item.getSsuCode())) {
                                item.setOrdProductNum(appSsuListVO.getOrdProductNum());
                                break;
                            }
                        }
                    }
                }
            }
        }
    }


    @ApiOperation(value = "小程序常用购买列表(senilon)", notes = "小程序常用购买列表")
    @GetMapping("product_purchase_list")
    public JsonResult<PtSsuSearchPageResult> mchPurchaseProductList(HttpServletRequest request, PtSsuBuyedPageAO ao) {
        Integer districtId = Integer.parseInt(request.getParameter("districtId"));
        String token = request.getHeader(TOKEN_PARAM_KEY);
        AccountCache cache = null;
        if (token != null) {
            cache = AccountUtils.getAccount(token);
        }

        if (cache == null) {
            cache = AccountUtils.getAccount();
        }

        String serialNo = AppUtils.newNo();
        PtSsuPurchasePageOrder ssuSearchOrder = new PtSsuPurchasePageOrder();
        ssuSearchOrder.setSerialNo(serialNo);
        ssuSearchOrder.setMchId(cache.getMchId());
        ssuSearchOrder.setDistrictId(districtId);
        if (null == ao.getPageNum()) {
            ao.setPageNum(1);
        }
        if (null == ao.getPageSize()) {
            ao.setPageSize(10);
        }
        // 获取登录的移动端
        ssuSearchOrder.setPage(new PageEntity<>(ao.getPageNum(), ao.getPageSize()));
        PtSsuSearchPageResult result = ptSsuFacade.mchPurchaseProductList(ssuSearchOrder);
        // 设置列表中购物车商品数量
        setCartProductNum(serialNo, result, token);
        return result.isSuccess() ? JsonUtils.success(result) : JsonUtils.fail(result.getMessage());
    }

    @ApiOperation(value = "小程序商品详情(senilon)", notes = "小程序商品详情")
    @GetMapping("product_detail")
    public JsonResult<PtSsuDetailResult> productDetail(HttpServletRequest request,PtSsuDetailAO ao) {
        String token = request.getHeader(TOKEN_PARAM_KEY);
        logger.info("token={}",token);
        AccountCache cache = null;
        if (token != null) {
            cache = AccountUtils.getAccount(token);
        }

        if (cache == null) {
            cache = AccountUtils.getAccount();
        }

        String serialNo = AppUtils.newNo();
        PtSsuDetailOrder order = new PtSsuDetailOrder();
        BeanUtils.copyProperties(ao, order);
        order.setSerialNo(serialNo);
        order.setMchId(cache.getMchId());
        PtSsuDetailResult result = ptSsuFacade.findSsuDetail(order);
        return result.isSuccess() ? JsonUtils.success(result)
                : JsonUtils.fail(result.getMessage());
    }


    @GetMapping("getShippingPrice")
    public JsonResult<SalesSetQueryResult> getShippingPrice() {
        SalesSetQueryResult salesSetQueryResult = new SalesSetQueryResult();
        salesSetQueryResult.setOrdShippingPrice(new Money(0));
        salesSetQueryResult.setOrdDeliverySatisfyPrice(new Money(0));
        salesSetQueryResult.setOrdDeliveryAuto(YNEnum.N);

        SalesSetQueryOrder salesSetQueryOrder = new SalesSetQueryOrder();
        String serialNo = AppUtils.newNo();
        salesSetQueryOrder.setSerialNo(serialNo);
        //添加查询用户对应会员标准
        String mchId = AccountUtils.getAccount().getMchId();
        salesSetQueryOrder.setMchId(mchId);
        SalesSetQueryResult result = salesSetFacade.salesSetQuery(salesSetQueryOrder);
        if (salesSetQueryResult.isFail()) {
            throw new BizError("销售订单设置查询错误！");
        }

        if (result.getOrdDeliveryAuto().getCode().equals(YNEnum.Y.getCode())) {
            return JsonUtils.success(result);
        }

        return JsonUtils.success(salesSetQueryResult);
    }

}
